<template>
  <div id="dialogPubCircle">
    <el-dialog class="about-set" title="添加我的动态" :visible.sync="dialogData.isShow" width="628px" top="80px" :before-close="labelHandleClose">
      <div class="form-box">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" class="demo-ruleForm">
          
          <el-form-item v-if="!this.dialogData.isVideo" label="关联活动" prop="activity.id">
            <el-select
              value-key="id"
              v-model="ruleForm.activity"
              filterable
              placeholder="选择活动"
            >
              <el-option
                v-for="item in activityList"
                :key="item.id"
                :label="item.name"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>

          <showTagSelect
            ref="tagSelect"
            :channel="channel"
            @getTagIds="getTagIds"
          ></showTagSelect>

          <el-form-item label="选择类型" prop="lifeType">
            <el-radio-group v-model="ruleForm.lifeType">
              <el-radio
                v-for="item in lifeTypeList"
                :key="item.dictValue"
                :label="item.dictValue"
              >
                {{ item.dictLabel }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="选择马甲" prop="userId">
            <el-select
              v-model="ruleForm.userId"
              filterable
              placeholder="请选择马甲"
              :disabled="ruleForm.canRobotRandom === true"
            >
              <el-option
                v-for="item in vestList"
                :key="item.robotId"
                :label="item.robotName"
                :value="item.robotId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="随机马甲">
            <el-switch
              v-model="ruleForm.canRobotRandom"
              :active-value="true"
              :inactive-value="false"
              active-color="#1DC8A4"
              @change="changeRandom(ruleForm.canRobotRandom)"
            ></el-switch>
            <span class="explain">注：都不选则默认以真实身份发布</span>
          </el-form-item>

          <el-form-item label="添加内容" prop="content">
            <el-input
              v-model="ruleForm.content"
              type="textarea"
              maxlength="200"
              show-word-limit
            ></el-input>
          </el-form-item>

          <!--作品类型为图文-->
          <el-form-item
            v-show="ruleForm.lifeType === 'TEXT'"
            label="添加动态作品"
            prop="imgJson"
          >
            <uploadImg from-page="pubLife" @setImgInfo="setImgInfo"></uploadImg>
          </el-form-item>
          <!--作品类型为小视频-->

          <el-form-item
            v-show="ruleForm.lifeType === 'VIDEO'"
            label="添加动态作品"
            prop="vid"
          >
            <el-button id="upload" type="warning">
              上传视频
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelLabel">取 消</el-button>
        <el-button type="success" :loading="loading" @click="confirmLabel('ruleForm')">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pubLife } from '@/api/lifeManagement' // 接口
import uploadImg from '@common/uploadImg' // 上传图片公共组件
import showTagSelect from '@common/showTagSelect' // 显性标签下拉选择公共组件
import { getVideoPara } from '@utils/pubFunction'
import { uploadVideo } from '@utils/uploadVideo'
import {
  sysNormalDisable,
  getVestList,
  getWorkListActivities,
  getRandomRobotId
} from '@utils/dictionariesFunc'
export default {
  name: 'dialogPubCircle',
  msg: '圈子管理-我的发布---发布作品',
  components: {
    uploadImg,
    showTagSelect
  },
  props: ['dialogData'],
  data() {
    return {
      loading: false,
      activityList: [{ id: '', name: '- 请选择关联活动 -', type: '' }], // 活动列表
      vestList: [{ robotId: '', robotName: '- 请选择马甲 -' }], // 选择马甲
      lifeTypeList: [], // 动态类型
      lifeDefaultTypeList: [], // 动态类型
      ruleForm: {
        activity: { id: '', name: '- 请选择关联活动 -', type: '' }, //活动对象
        activityType: '',
        activityId: '', //活动id
        userId: '', // 用户id
        canRobotRandom: false, //是否为随机马甲，为true的话系统后端默认随机一个马甲
        lifeType: 'TEXT', // 动态类型
        content: '', // 动态内容
        imgJson: '', // 图片信息
        vid: '', // 视频vid
        coverImg: '', //封面图
        tagId: 0,
        postType: 'POST', //帖子类型,主贴id不为空时值必为 FOLLOWCOPY  [POST（帖子）/  FOLLOWCOPY（跟帖）]
        plainText: '', // 必传 如内容为富文本类型, 此字段传 去除富文本后的纯文本
        textType: 'SIMPLETEXT' //RICKTEXT（富文本）/ SIMPLETEXT（普通文本）
      },
      rules: {
        'activity.activityId': { /*required: true,*/ message: '请选择活动' },
        userId: {},
        lifeType: { required: true, message: '请选择动态作品类型' },
        content: {
          required: true,
          message: '动态内容不能为空',
          trigger: 'change'
        },
        imgJson: { required: true, message: '请上传动态作品图片' },
        vid: {}
      },
      polivNum: {
        polyvUserId: '',
        polyvSecretKey: '',
        polyvWriteToken: '',
        polyvReadToken: ''
      },
      upVideo: null,
      channel: 'LIFE',
      labelItems: []
    }
  },
  computed: {
    dapengUserId() {
      return this.$store.state.user.dapengUserId
    }
  },
  watch: {
    'ruleForm.lifeType': {
      // 监听类型
      handler(newValue, oldValue) {
        let channel = ''
        if (newValue === 'VIDEO') {
          /*console.log('VIDEO')*/
          // 视频
          this.rules.imgJson = {}
          this.rules.vid = { required: true, message: '请上传视频' }
          channel = 'SHORT_VIDEO'
        } else {
          /* console.log('TEXT')*/
          // 图文
          this.rules.imgJson = { required: true, message: '请上传动态作品图片' }
          this.rules.vid = {}
          channel = 'LIFE'
        }
        this.labelItems = []
        this.$refs.tagSelect.clearTagIds()
        this.$refs.tagSelect.getTagList(channel)
      },
      deep: true
    },
    'ruleForm.activity': {
      // 监听关联活动
      handler(newValue, oldValue) {
        if (newValue.id) {
          //选中关联活动
          if (this.lifeTypeList.length > 1) {
            this.lifeTypeList.splice(1, 1)
            this.ruleForm.lifeType = this.lifeTypeList[0].dictValue
          }
          this.ruleForm.activityId = newValue.id
          this.ruleForm.activityType = newValue.type
        } else {
          this.lifeTypeList = [...this.lifeDefaultTypeList]
          this.ruleForm.activityId = ''
          this.ruleForm.activityType = ''
        }
      },
      deep: true
    }
  },
  mounted() {
    if (this.dialogData.isVideo) {
      this.ruleForm.lifeType = 'VIDEO'
      this.channel = 'SHORT_VIDEO'
    }
    this.getStatusList()
    this.getPolivNum()
  },
  methods: {
    /* 获取系统配置-保利威视 */
    getPolivNum() {
      let _this = this
      getVideoPara().then((data) => {
        this.polivNum = { ...data }
        uploadVideo(_this.polivNum, _this.saveVideo).then((resObj) => {
          _this.upVideo = resObj
        })
      })
    },
    /* 保存上传视频 */
    async saveVideo(fileData) {
      this.ruleForm.vid = fileData.vid
    },
    /* 获取数据状态 */
    async getStatusList() {
      // 动态类型
      let data2 = await sysNormalDisable('sys_work_type')
      this.lifeDefaultTypeList = [...data2]
      this.lifeTypeList = [...data2]
      if (this.dialogData.isVideo) {
        //来自动态小视频发布页面，只显示短视频radio
        this.lifeTypeList.splice(0, 1)
      }
      // 活动列表
      if (!this.dialogData.isVideo) {
        //来自动态小视频发布页面，只显示短视频radio
        let data = await getWorkListActivities('LIFE', { stauts: 'ONGOING' })
        this.activityList = this.activityList.concat(data)
        this.ruleForm.activity = this.activityList[0]
      }
      // 马甲
      let data1 = await getVestList(this.dapengUserId)
      this.vestList = this.vestList.concat(data1)
    },
    labelHandleClose(done) {
      this.cancelLabel()
      done()
    },
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.upVideo.update({
        uploadSuccess: ''
      })
      clearInterval(this.upVideo.timer)
      this.upVideo.destroy()
      this.dialogData.isShow = false
      this.dialogData.isVideo = null
    },
    /* 图片上传成功后，获取返回结果 */
    setImgInfo(str) {
      this.ruleForm.imgJson = str
    },
    /* 改变随机马甲按钮状态 */
    changeRandom(status) {
      if (status === true) {
        // 启用随机马甲
        if (this.vestList.length === 0) {
          this.$message({
            message: '马甲列表为空，无法选择随机马甲',
            type: 'error'
          })
          this.ruleForm.canRobotRandom = true
        }
      }
    },
    /*整合选择的标签*/
    setIabelInfos() {
      let ary = []
      this.labelItems.forEach((item, index) => {
        let { labelProperty: labelCategoryProperty, labelId, labelName } = item
        let obj = {
          labelCategoryProperty,
          labelId,
          labelName
        }
        ary.push(obj)
      })
      return [...ary]
    },
    /* 确认提交 */
    async confirmLabel(formName) {
      this.loading = true
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let obj = { ...this.ruleForm }
          // userId,随机马甲时，取随机马甲，否则取当前马甲的robotId
          if (this.ruleForm.canRobotRandom === true) {
            obj.userId = (await getRandomRobotId(this.dapengUserId)) || ''
          }
          if (obj.lifeType === 'VIDEO') {
            obj.imgJson = []
          }
          obj.plainText = obj.content
          delete obj.activity
          //选中标签
          obj.labelInfos = this.setIabelInfos()
          pubLife(
            obj,
            (response) => {
              this.loading = false
              this.$emit('refresh')
              this.cancelLabel()
            },
            (response) => {
              this.loading = false
              this.$message.warning('发布失败，' + response.message)
            }
          )
        } else {
          this.loading = false
          return false
        }
      })
    },
    /* 获取选中的显性标签 */
    getTagIds(items) {
      this.labelItems = [...items]
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
#dialogPubCircle {
  @import url('~@common/style/textarea.less');
  .explain {
    margin-left: 8px;
  }
}
</style>
